import { RoleEntity } from './../../../role/entities/role.entity';
import { AccountRoleEntity } from './../../entities/account.role.entity';
import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getManager, EntityManager, getConnection } from 'typeorm';
import { MutationRes } from 'src/modules/shared/vo/mutation.res';
import { CreateAccountRoleInput } from '../../resolvers/account-role/dto/create.account.role.input';

@Injectable()
export class AccountRoleService {
    constructor (
        @InjectRepository(AccountRoleEntity)
        private readonly accountRoleRepository: Repository<AccountRoleEntity>,
    ) { }


    async createAccountRole(createAccountRoleInput: CreateAccountRoleInput): Promise<MutationRes> {
        const { accountId, roleIdList } = createAccountRoleInput;
        return getManager()
            .transaction(async (entityManager: EntityManager) => {
                await entityManager.delete(AccountRoleEntity, { accountId: Number(accountId) });
                for (const item of roleIdList) {
                    await entityManager.save(AccountRoleEntity, { accountId, roleId: Number(item) });
                }
            }).then(async () => {
                return {
                    code: 0,
                    message: '成功',
                };
            }).catch((e) => {
                Logger.error('账号分配角色错误', e);
                throw new HttpException('账号分配角色错误', HttpStatus.OK);
            });
    }

   
    async roleListByAccountId(accountId: number): Promise<RoleEntity[]> {
        // 获取全部的角色id
        const roleLists = await this.accountRoleRepository.find({ where: { accountId }, select: ['roleId'] });
        const roleList = roleLists.map(item => item.roleId);
        if (roleList.length) {
            // 查询全部的角色
            return await getConnection().createQueryBuilder(RoleEntity, 'role')
                .where('(role.id in (:...roleId))', { roleId: roleList })
                .getMany()
        } else {
            return [];
        }
    }
}
